package model;

import java.io.IOException;
import java.net.ConnectException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 *
 * @author Dustin
 */
public class Peer {
    public final static int DEFAULT_PORT = 65432;

    private boolean connected;
    private ServerSocket serverSocket;
    private Socket socket;
    private Queue sendQueue = new Queue();
    private Queue receiveQueue = new Queue();
    private ReceiveWindow receiveWindow;
    private SendWindow sendWindow;
    private HigherLayer higherLayer;

    public void connect(String host) {
        boolean sender = false;
        if(!connected) {
            try {
                System.out.println("Trying socket");
                socket = new Socket(host, DEFAULT_PORT);
                connected = true;
            } catch (ConnectException ex) {
                try {
                    System.out.println("Trying server socket");
                    serverSocket = new ServerSocket(DEFAULT_PORT);
                    sender = true;
                    while(!connected) {
                        socket = serverSocket.accept();
                        connected = true;
                        System.out.println("Accepted socket");
                    }
                } catch (IOException ex1) {
                    ex1.printStackTrace();
                }
            }
            catch (UnknownHostException ex) {
                ex.printStackTrace();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            System.out.println("Creating IO");
            sendWindow = new SendWindow(sendQueue);
            higherLayer = new HigherLayer(sendWindow);
            receiveWindow = new ReceiveWindow(receiveQueue, higherLayer);

            receiveWindow.setSendWindow(sendWindow);
            sendWindow.setReceiveWindow(receiveWindow);
            receiveWindow.start();
            sendWindow.start();

            new SendThread(socket, sendQueue).start();
            new ReceiveThread(socket, receiveQueue).start();
            System.out.println("Connected");

            if(sender) {
                Object[] data  = new Object[26];
                char x = 'a';
                for(int i = 0; i < data.length; i++) {
                    data[i] = (char) x++;
                }
                higherLayer.send(data);
            }
        }
    }

    public static void main(String[] args) {
        new Peer().connect("145.76.106.43");
    }
}
